package com.steven.sync.mianshi;


import java.util.LinkedList;

/**
 * 固定同步容器，put get ，getcount方法，支持2个生产者，10个消费者调用 阻塞调用
 */
public class Test2_p_c_notify {

    static LinkedList list = new LinkedList<>();

    static final private Integer MAX =10;

    public void  put (Object o){
        list.add(o);
        System.out.println(Thread.currentThread().getName()+"生产");
    }
    public void  get (Object o){
        list.removeFirst();
        System.out.println(Thread.currentThread().getName()+"消费");
    }
    public Integer  getCount(){
       return list.size();
    }

    public static void main(String[] args) {
        Test2_p_c_notify test2Pcnotify = new Test2_p_c_notify();

        //生产者
        for (int i = 0; i < 2; i++) {
            new Thread(()->{
                for (int j = 0; j < 10; j++) {
                    synchronized (test2Pcnotify){
                        while (test2Pcnotify.getCount() == MAX){
                            try {
                                test2Pcnotify.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        test2Pcnotify.put(new Object());
                        System.out.println(Thread.currentThread().getName() + "-生产者生产，数量为:" + test2Pcnotify.getCount());
                        test2Pcnotify.notifyAll();
                    }
                }

            },"P"+i).start();
        }



        //消费者
        for (int i = 0; i < 9; i++) {
            new Thread(()->{
                for (int j = 0; j < 10; j++) {

                    synchronized (test2Pcnotify){
                        while (test2Pcnotify.getCount() ==0){
                            try {
                                test2Pcnotify.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        test2Pcnotify.get(new Object());
                        System.out.println(Thread.currentThread().getName() + "-消费者消费，数量为："+ test2Pcnotify.getCount());
                        test2Pcnotify.notifyAll();
                    }
                }
            },"C"+i).start();
        }




    }




}
